<template>
  <div class="dictionary-management-container">
    <el-row :gutter="20">
      <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-button
            class="tree-button"
            :icon="Plus"
            type="primary"
            @click="handleEdit()"
          >
            添加字典分类
          </el-button>
          <el-input v-model="filterText" placeholder="请输入字典分类名称" />
          <el-tree
            ref="treeRef"
            :data="dictTypeData"
            default-expand-all
            :filter-node-method="filterNode"
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="dictType-item">
                <span>{{ node.label }}</span>
                <div>
                  <a v-if="data.id > 0" @click="handleEdit(node, data)">编辑</a>
                  <a
                    v-if="!data.children"
                    v-permissions="{
                      role: [''],
                      permission: ['sys:dictclassification:delete'],
                    }"
                    style="margin-left: 4px"
                    @click="remove(node, data)"
                  >
                    删除
                  </a>
                </div>
              </div>
            </template>
          </el-tree>
        </vab-card>
      </el-col>
      <el-col :lg="20" :md="16" :sm="24" :xl="20" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-button
                v-if="row && row.code"
                :icon="Plus"
                type="primary"
                @click="handleAddDict()"
              >
                添加
              </el-button>
            </vab-query-form-top-panel>
          </vab-query-form>
          <el-table v-loading="listLoading" border :data="list">
            <el-table-column
              label="id"
              prop="id"
              width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="字典名称"
              prop="name"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="字典值"
              prop="value"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="字典颜色"
              prop="dictColor"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="排序"
              prop="sort"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="操作"
              show-overflow-tooltip
              width="200"
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <el-button text type="primary" @click="handleDictEdit(row)">
                  编辑
                </el-button>
                <el-button text type="primary" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty class="vab-data-empty" description="暂无数据" />
            </template>
          </el-table>
        </vab-card>
      </el-col>
    </el-row>
    <dict-edit ref="editRef" @fetch-data="fetchDictTypeData" />
    <edit ref="dictRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    fetchDictList,
    fetchDictTypesList,
    deleteDict,
    deleteDictType,
  } from '@/api/dictionaryManagement'
  import { Plus } from '@element-plus/icons-vue'
  import { useAclStore } from '@/store/modules/acl'
  export default defineComponent({
    name: 'DictionaryManagement',
    components: {
      DictEdit: defineAsyncComponent(() =>
        import('./components/DictiTypeEdit')
      ),
      Edit: defineAsyncComponent(() => import('./components/DictEdit')),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const aclStore = useAclStore()
      const { role, permission } = storeToRefs(aclStore)
      const state = reactive({
        treeRef: null,
        editRef: null,
        dictRef: null,
        dictTypeData: [], // 字典类型数据
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        list: [], // 字典数据
        listLoading: false,
        row: null,
      })

      const handleEdit = (row) => {
        state['editRef'].showEdit(row)
      }

      const handleDictEdit = (row) => {
        row.typeCode = state.row.code
        state['dictRef'].showEdit(row)
      }
      const handleAddDict = () => {
        state['dictRef'].showEdit({
          typeCode: state.row.code,
        })
      }
      const handleDelete = (row) => {
        if (row.id) {
          try {
            $baseConfirm('你确定要删除当前项吗', null, async () => {
              const { msg } = await deleteDict({ ids: row.id })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await getDictTypeList()
              await fetchData()
            })
          } catch (e) {
            console.error(e)
          }
        }
      }
      const fetchData = async (code = '') => {
        state.listLoading = true
        try {
          const params = {
            keywords: '',
            typeCode: code || state.row.code,
            pageNum: 1,
            pageSize: 999,
          }
          const {
            data: { list },
          } = await fetchDictList(params)
          state.list = list
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }
      const handleNodeClick = (data) => {
        state.row = data
        if (data.id > 0) {
          fetchData(data.code)
        }
      }

      const filterText = ref('')
      watch(filterText, (value) => {
        state.treeRef.filter(value)
      })

      const filterNode = (value, data) => {
        if (!value) return true
        return data.label.includes(value)
      }

      const getDictTypeList = async () => {
        try {
          const params = {
            keywords: '',
            pageNum: 1,
            pageSize: 999,
          }
          const { data } = await fetchDictTypesList(params)
          const allData = [
            {
              id: 0,
              code: 'root',
              name: '全部',
              status: 1,
              children: [],
            },
          ]
          allData[0].children = data.list || []
          state.dictTypeData = allData
        } catch (e) {
          console.error(e)
        }
      }
      const fetchDictTypeData = () => {
        getDictTypeList()
      }
      const remove = (node, data) => {
        try {
          $baseConfirm('你确定要删除当前字典分类吗', null, async () => {
            try {
              const { msg } = await deleteDictType({ ids: data.id })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await getDictTypeList()
            } catch (e) {
              console.error(e)
            }
          })
        } catch (e) {
          console.error(e)
        }
      }

      onMounted(() => {
        getDictTypeList()
      })

      return {
        ...toRefs(state),
        filterText,
        filterNode,
        remove,
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        fetchDictTypeData,
        handleDictEdit,
        handleAddDict,
        role,
        permission,
        Plus,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.dictionary-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;

    .tree-button {
      width: 100%;
      margin-bottom: $base-margin;
    }

    :deep() {
      .el-tree {
        margin-top: $base-margin;

        &-node__label {
          display: block;
          width: 100%;
        }
      }
    }
  }
  .dictType-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
</style>
